package baseline;

import java.util.HashMap;
import java.util.Iterator;

public class TrainingFile extends FileParser {
  private String trainingFileName_;
  HashMap<String, WordStat> wordStats_;
  HashMap<String, Integer> tagCounts_;
  String bestTag_;

  public TrainingFile(String fileName) throws FileParser.FPException {
    super();
    super.parseFile(fileName);

    trainingFileName_ = fileName;

    wordStats_ = new HashMap<String, WordStat>();
    tagCounts_ = new HashMap<String, Integer>();
    processTrainingFile();
  }

  void processTrainingFile() {
    // Add all the tags.
    for (int i = 0; i < words_.size(); ++i) {
      final String currWord = words_.get(i);
      final String currTag = tags_.get(i);

      WordStat ws = wordStats_.get(currWord);
      if (ws == null) {
        ws = new WordStat(currTag);
        wordStats_.put(currWord, ws);
      } else {
        ws.addTag(currTag);
      }

      Integer tagCount = tagCounts_.get(currTag);
      if (tagCount == null) {
        tagCounts_.put(currTag, 1);
      } else {
        tagCounts_.put(currTag, tagCount + 1);
      }
    }

    // Process the tag counts.
    Iterator<String> tcit = tagCounts_.keySet().iterator();
    int maxCount = -1;
    String maxTag = null;
    while (tcit.hasNext()) {
      String currTag = (String) tcit.next();
      Integer tagCount = tagCounts_.get(currTag);

      if (tagCount > maxCount) {
        maxCount = tagCount;
        maxTag = currTag;
      }
    }
    bestTag_ = maxTag;

    Iterator<String> wsit = wordStats_.keySet().iterator();
    while (wsit.hasNext()) {
      WordStat ws = wordStats_.get(wsit.next());
      ws.process();
    }
  }

  public String getBestTag(String word) {
    WordStat ws = wordStats_.get(word);

    if (ws == null) {
      return "NNP";
    } else {
      return ws.getBestTag();
    }
  }

  public String getTrainingFileName() {
    return trainingFileName_;
  }
}
